<template>
  <view class="login-grzq">
    <view class="shading">
      <image :src="logoUrl" />
    </view>
    <view class="shading_title">
      <image :src="logoszqUrl"></image>
    </view>
    <view class="register_title">
      <view>你好，欢迎使用国润甄泉</view>
    </view>
    <view class="form">
      <view class="inputs_button">
        <view class="inputs">
          <view class="account">
            <input type="number" v-model="account" :adjust-position="false" placeholder="请输入手机号" />
          </view>
          <view class="password" v-if="loginType == 1">
            <input :type="pwdShow ? 'text' : 'password'" v-model="password" :adjust-position="false"
              placeholder="请输入密码" />
            <uni-icons :type="pwdShow ? 'eye-filled' : 'eye-slash-filled'" size="24" color="#cccccc"
              @click="pwdShow = !pwdShow"></uni-icons>
          </view>
          <view class="vcode" v-if="loginType == 2">
            <input type="number" v-model="vcode" :adjust-position="false" placeholder="验证码" />
            <text v-if="vcodeTime == 0" style="color:#3264ed" @click="getVcode">获取验证码</text>
            <text v-else style="color:#ccc">重新获取({{ vcodeTime }}s)</text>
          </view>
        </view>
        <!--        <view class="codeSwitch" @click="codeSwitchClick">
          <image :src="codeSwitch.img"/>
          <text>{{
              codeSwitch.title
            }}
          </text>
        </view>-->

        <view class="button">
          <!--          <view @click="loginMobile" v-if="current === 1">  登录  </view>-->
          <view @click="submit_register"> 登 &nbsp; &nbsp; 录</view>
        </view>
      </view>
     
      <view class="login_register">
        <text @click="registerAccount">注册账户</text>
        <text class="register_tit">|</text>
        <text @click="forgetPwd">忘记密码</text> 
      </view>
      <view class="login-weixin">
        <view class="login-divider"><view style="margin: 0 10rpx;">手机号快捷登录</view></view>
        <button class="weixin-btn" v-if="bindPhone === false" open-type="getPhoneNumber"
          @getphonenumber="onGetPhoneNumber">
          <image :src="phoneUrl"></image>
        </button>
        <button class="weixin-btn" v-else @click="jumpNewPage">
          <image :src="phoneUrl"></image></button>
      </view>
    </view>
    <view class="pact">
      <radio :checked="pactChecked" @animationend="inAnimation = false" activeBorderColor="#3264ed"
        borderColor="#3264ed" color="#3264ed" @click="pactChange" />
      <view>我已阅读并同意
        <text @click="privacy(4)">《用户协议》</text>
        和
        <text @click="privacy(3)">《隐私协议》</text>
      </view>
    </view>
  </view>
</template>

<script>
const app = getApp();
import { phoneLogin, phoneRegister, verifyCode, registerVerify } from "@/api/api";

const BACK_URL = 'login_back_url';
import Routine from '@/libs/routine';
import {
  routineBindingPhone,
  wechatAuthLogin,
  authType,
  silenceAuth
} from '@/api/public';
export default {
  data() {
    return {
      inAnimation: false,
      logoUrl: this.$common.imgUrl() + '/images/logo@2x.png',
      logoszqUrl: this.$common.imgUrl() + '/images/login/szq@2x.png',
      phoneUrl: this.$common.imgUrl() + '/images/login/phone.png',
      codeSwitch: {
        t: 1,
        title: "验证码登陆",
        img: this.$common.imgUrl() + '/images/member/zyIcon.png'
      },
      account: "",
      password: "",
      vcode: "",
      loginType: 1,
      pwdShow: false,
      pactChecked: false,
      vcodeTime: 0,
      vcodeTimer: null,
      keyLock: true,// 验证码 重复点击
      authKey: '',
      openid: '',
      access_token: '',
      access_token_key: '',
      userInfo: {},
      bindPhone: false,//是否绑定手机号
    }
  },
  onLoad() {
    this.userLogin()
  },
  methods: {
    userLogin() {
      Routine.getCode()
        .then(code => {
          silenceAuth({
            code,
            spread_spid: app.globalData.spid,
            spread_code: app.globalData.code
          }).then(res => {
            this.userInfo = res.data.user_info
            this.bindPhone = res.data.bindPhone
            this.access_token_key = res.data.access_token_key;
            this.authKey = res.data.session_key;
            this.openid = res.data.openid
            this.access_token = res.data.access_token
          })
        })
        .catch(err => {
          console.log(err)
        });
    },
    // 点击第三方登录
    onGetPhoneNumber(e) {
      if (e.detail.errMsg === "getPhoneNumber:ok") {
        const encryptedData = e.detail.encryptedData;
        const iv = e.detail.iv;
        const code = e.detail.code;
        this.decryptPhoneNumber(encryptedData, iv, code);
      } else {
        console.log("用户拒绝了授权");
      }
    },
    // 绑定手机号
    decryptPhoneNumber(encryptedData, iv, code) {
      // 根据手机号获取信息 后端回调
      routineBindingPhone({
        encryptedData: encryptedData,
        iv: iv,
        code: code,
        spread_spid: app.globalData.spid || '',
        spread_code: app.globalData.code || '',
        key: this.authKey,
        openid: this.openid,
        access_token_key: this.access_token_key
      })
        .then(res => {
          if (res.status === 200) {
            this.jumpNewPage()
            //  绑定以后跳转操作
          } else {
            console.log("授权失败");
          }
        })
        .catch(res => {
          uni.hideLoading();
        });
    },
    jumpNewPage() {
      uni.showLoading({
        title: '正在登录'
      });
      setTimeout(() => {
        uni.hideLoading();
        let backUrl = '/pages/index/home';
        this.$store.commit('LOGIN', {
          token: this.access_token,
          time: this.$Cache.time()
        });
        uni.reLaunch({
          url: backUrl
        });
        this.$store.commit('SETUID', this.userInfo.id);
        this.$store.commit("UPDATE_USERINFO", this.userInfo);
        this.$store.commit("UPDATE_USERINFO_ROLE", this.userInfo.water_role);
        // this.$store.commit("UPDATE_USERINFO_ROLE", 'buy');
      }, 1000);

    },
    login() {
      uni.showToast({
        title: "登录方式" + this.loginType,
        icon: 'none'
      })
    },
    async loginMobile() {
      let that = this;
      if (!that.protocol) {
        this.inAnimation = true;
        return that.$utils.Tips({
          title: '请先阅读并同意协议'
        });
      }
      if (!that.account)
        return that.$utils.Tips({
          title: '请填写手机号码'
        });
      if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account))
        return that.$utils.Tips({
          title: '请输入正确的手机号码'
        });
      if (!that.captcha)
        return that.$utils.Tips({
          title: '请填写验证码'
        });
      phoneLogin({ 'account': that.account, 'password': that.password }).then(res => {
        console.log("登录成功")
        console.log(res)

        self.$store.commit('SETUID', res.data.userInfo.uid);
        self.$store.commit('setUserInfo', res.data.userInfo);
      })
    },
    async submit_register() {
      let that = this;
      if (!that.pactChecked) {
        this.inAnimation = true;
        return that.$utils.Tips({
          title: '请先阅读并同意协议'
        });
      }
      if (!that.account)
        return that.$utils.Tips({
          title: '请填写账号'
        });
      if (!/^[\w\d]{5,16}$/i.test(that.account))
        return that.$utils.Tips({
          title: '请输入正确的账号'
        });
      if (!that.password)
        return that.$utils.Tips({
          title: '请填写密码'
        });
      phoneLogin({ 'account': that.account, 'password': that.password }).then(res => {
        console.log("登录成功")
        console.log(res)
        let water_role = res.data.user_info.water_role ?? false;
        console.log('类型', water_role)
        //
        if (water_role == false) {
          return that.$utils.Tips({
            title: '暂无权限，请联系官方客服'
          })
        } else {
          that.$store.commit('LOGIN', {
            token: res.data.token,
            time: res.data.expires_time - that.$Cache.time()
          });
          // 管理员、购买者index
          // 普通用户 index_my
          let backUrl = '';
          if (water_role == "manage") {
            backUrl = '/pages/user/index';
          } else if (water_role == "buy") {
            backUrl = '/pages/user/index';
          } else if (water_role == "intake") {
            backUrl = '/pages/index/home';
          } else {
            backUrl = '/pages/index/home';
          }

          // self.$Cache.clear(BACK_URL);
          that.$store.commit('SETUID', res.data.uid);
          that.$store.commit("UPDATE_USERINFO", res.data.user_info);
          that.$store.commit("UPDATE_USERINFO_ROLE", water_role);
          // that.$store.commit("UPDATE_USERINFO_ROLE", 'buy');
          uni.reLaunch({
            url: backUrl
          });
        }

      })

    },
    getVcode() {
      this.vcodeTime = 60
      this.vcodeTimer = setInterval(() => {
        if (this.vcodeTime > 0) {
          this.vcodeTime--
        } else {
          clearInterval(this.vcodeTimer)
          this.vcodeTimer = null
        }
      }, 1000)
      uni.showToast({
        title: "获取验证码",
        icon: 'none'
      })
    },
    codeSwitchClick() {
      // 切换
      if (this.codeSwitch.t == 1) {
        this.loginType = 1;
        this.codeSwitch.title = "验证码登陆";
      } else {
        this.loginType = 2;
        this.codeSwitch.title = '密码登陆'
      }
    },
    pactChange() {
      this.pactChecked = !this.pactChecked
      console.log(this.pactChecked)
    },
    registerAccount() {
      console.log("切换注册账户");
      // this.loginType = 2;

      uni.navigateTo({
        url: '/pages/login/register'
      })

    },
    forgetPwd() {
      console.log("忘记密码")
      uni.navigateTo({
        url: "/pages/login/retrievePassword"
      })
    },
    privacy(type) {
      console.log(type)
      uni.navigateTo({
        url: '/pages/users_purchasing/privacy/index?type=' + type
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.login-grzq {
  min-height: 100vh;
  background: url($baseUrl + '/images/bg/login@2x.png') no-repeat top center;
  background-size: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .shading {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;

    /* #ifdef APP-VUE */
    margin-top: 50rpx;
    /* #endif */
    /* #ifndef APP-VUE */

    margin-top: 180rpx;
    /* #endif */

    image {
      width: 200rpx;
      height: 200rpx;
    }
  }

  .shading_title {
    display: flex;
    align-items: center;
    width: 100%;
    justify-content: center;

    image {
      width: 200rpx;
      height: 50rpx;
      padding-top: 13rpx;
    }
  }

  .register_title {
    padding-top: 53rpx;

    view {
      padding-left: 64rpx;
      font-size: 33rpx;
      font-weight: 600;
      color: #383838;
    }
  }

  .title {
    padding-top: 20rpx;
    // padding-bottom: 70rpx;

    view {
      padding-left: 64rpx;
      font-size: 18rpx;
      font-weight: 700;
      color: #383838;
    }
  }

  .form {
    flex: 1;
    margin: 0 32rpx;
    border-radius: 40rpx;
    // background-color: #fff;
    overflow: hidden;

    .inputs_button {
      .inputs {
        padding: 24rpx 32rpx 0;
        margin-bottom: 80rpx;

        .account,
        .password,
        .vcode {
          height: 96rpx;
          border-radius: 20rpx;
          padding: 0 48rpx;
          display: flex;
          align-items: center;
          background: url($baseUrl + '/images/login/imput.png') no-repeat top center;

          input {
            flex: 1;
          }
        }

        .account {
          margin-bottom: 48rpx;
        }

        .vcode {
          text {
            text-wrap: nowrap;
            font-size: 26rpx;
            background-color: #fff;
            padding: 14rpx 30rpx;
            border-radius: 12rpx;
          }
        }
      }

      .codeSwitch {
        height: 50rpx;
        width: 300rpx;
        color: #3264ed;

        image {
          width: 45rpx;
          height: 43rpx;
          padding-right: 2rpx;
        }

        text {
          font-size: 24rpx;
        }

      }

      .button {
        padding: 0 32rpx;

        view {
          line-height: 96rpx;
          border-radius: 20rpx;
          text-align: center;
          font-size: 32rpx;
          background-color: #3264ed;
          color: #fff;
        }
      }
    }

  }

  .login-weixin {
    text-align: center;
    margin-top: 20rpx;
    font-size: 21rpx;
    color: #bbb;
    .login-divider {
        color: #999;
        margin: 40rpx 0 21rpx 0;
        position: relative;
        // padding:10rpx;
    }

    .login-divider::before,
    .login-divider::after {
        content: "";
        position: absolute;
        top: 50%;
        width: 35%;
        height: 1px;
        background-color: #eee;
    }

    .login-divider::before {
        left: 0;
    }

    .login-divider::after {
        right: 0;
    }

    .weixin-btn {
      background-color: #fff;
      border: none !important;
      height: 80rpx;
      line-height: 50rpx;
      image{
        width: 79rpx;
        height: 79rpx;
      }
    }

    wx-button:after {
      border: 1px solid #fff;
    }
  }

  .login_register {
    padding-top: 20rpx;
    display: flex;
    align-items: center;
    width: 100%;
    justify-content: center;
    color: #3264ed;

    text {}

    .register_tit {
      padding: 0 75rpx;
    }
  }

  .pact {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-bottom: 90rpx;
    font-size: 24rpx;

    text {
      color: #3264ed;
    }

    radio {
      :deep(.uni-radio-input) {
        border: 1rpx solid #3264ed;
      }

      transform: scale(0.6)
    }
  }
}
</style>
